package com.eureka.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.eureka.bclass.util.LoggerUtil;
import com.eureka.bclass.util.RequestUtil;
import com.eureka.pay.configurer.properties.AdvancePaymentProperties;
import com.eureka.pay.configurer.properties.AdvancePaymentPropertiesConfig;
import com.eureka.pay.enums.ClientEnum;
import com.eureka.pay.service.AlibabaPayCallbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Map;

/**
 * @Description: 阿里巴巴支付回调服务
 * @Author: lixing
 * @Date: 2021/7/9 8:22
 */
@Service
public class AlibabaPayCallbackServiceImpl implements AlibabaPayCallbackService {
    /**
     * 预支付信息
     */
    @Autowired
    private AdvancePaymentPropertiesConfig advancePaymentPropertiesConfig;

    /**
     * @Description 支付成功后，点击页面的完成按钮后回调
     * @Author lixing
     * @Date 2021/7/9 8:23
     * @Param [request]
     */
    @Override
    public ModelAndView returnUrl(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("alibabaReturnSuccessPage");
    }

    /**
     * @Description 支付成功异步回调
     * @Author lixing
     * @Date 2021/7/9 8:24
     * @Param [request]
     *
     *    // 异步通知参数 https://opendocs.alipay.com/open/203/105286
     *    {
     *        gmt_create = 2021-07-09 10:42:09,
     *        charset = UTF-8,
     *        seller_email = laohugy @e7895.com,
     *        subject = 升级企业用户,
     *        sign = jdTDcODEuXObdRcaItdtqCNgvZ0PlqtVyh9O489syUob5aRt0pwa2xtzvF2QSsKCnhvtIw3pXdtdMn5rIW+C48yeYeLzrjBwtmkPLJPPuFsVo8egX6rNeJTizqhVmWD9FvDR+A2XsbAk6j/PQzp75LH5ZAKr8fnNuf4ZKT9p5tGbE7UUPgQliDaIxFm2ijUsIAZo0iGxu9raL+IdsZkG0gUa+R3aXdaUYa10wkfFdtQPGUQblBqlWaKXiDMym20Xoz91D+9GwjwmlibrTdfz/1TJJQLWW3+HkBpc9rAaMprDHSI8Rs3GVOSBuLPdEWiAc2SfIVMaw2K++wO1T83S3A==,
     *        body=升级企业用户,
     *        buyer_id = 2088702226406461,
     *        invoice_amount = 0.01,
     *        notify_id = 2021070900222104209006461455722634,
     *        fund_bill_list = [{"amount": "0.01","fundChannel": "PCREDIT" }],
     *        notify_type = trade_status_sync,
     *        trade_status = TRADE_SUCCESS,
     *        receipt_amount = 0.01,
     *        buyer_pay_amount = 0.01,
     *        app_id = 2021002156654351,
     *        sign_type = RSA2,
     *        seller_id = 2088141842684585,
     *        gmt_payment = 2021-07-09 10:42:09,
     *        notify_time = 2021-07-09 10:42:10,
     *        passback_params = {"businessType": "100000"},
     *    	 version = 1.0,
     *    	 out_trade_no = 10000016257985154200,
     *    	 total_amount = 0.01,
     *    	 trade_no = 2021070922001406461425161640,
     *    	 auth_app_id = 2021002156654351,
     *    	 buyer_logon_id = 735 ** * @qq.com,
     *    	 point_amount = 0.00
     *    }
     */
    @Override
    public void notifyUrl(HttpServletRequest request) throws IOException, AlipayApiException {
        // 回调参数
        //String resParamStr = RequestUtil.getRequestParam(request);
        //LinkedHashMap<String, String> linkedHashMap = formatCallbackParam(resParamStr);
        Map<String, String> linkedHashMap = RequestUtil.getRequestParamForAlibaba(request);
        /*
         * 订单信息
         */
        // 订单编号
        String tradeNo = linkedHashMap.get("trade_no");
        // 订单金额
        String totalAmount = linkedHashMap.get("total_amount");
        // 公共回传参数，如果请求时传递了该参数，则返回给商户时会在异步通知时将该参数原样返回。本参数必须进行UrlEncode之后才可以发送给支付宝
        String passbackParams = linkedHashMap.get("passback_params");
        JSONObject passbackParamsObj = JSONObject.parseObject(passbackParams);
        // 买家支付宝账号
        String buyerLogonId = linkedHashMap.get("buyer_logon_id");
        // 该笔交易的买家付款时间
        String gmtPayment = linkedHashMap.get("gmt_payment");
        // 交易状态：交易支付成功：TRADE_SUCCESS
        String tradeStatus = linkedHashMap.get("trade_status");
        if (!"TRADE_SUCCESS".equals(tradeStatus)) {
            LoggerUtil.error(MessageFormat.format("【支付宝】买家：{0} 于 {1} 支付金额 {2} 异步回调验签失败，订单编号：{3} 交易状态：TRADE_FAIL", buyerLogonId, gmtPayment, totalAmount, tradeNo, tradeStatus));
        } else {
            /*
             * 根据 businessType 获取 相关参数
             */
            String businessType = passbackParamsObj.getString("businessType");
            long userId = passbackParamsObj.getLong("userId");
            AdvancePaymentProperties advancePaymentProperties = advancePaymentPropertiesConfig.getParamsByBusinessType(ClientEnum.ALIBABA.getClient(), businessType, userId);
            /*
             * 验签
             */
            boolean signVerified = AlipaySignature.rsaCheckV1(linkedHashMap, advancePaymentProperties.getAlibabaRsaPublicKey(), advancePaymentProperties.getAlibabaCharset(), advancePaymentProperties.getAlibabaSignType());
            if (signVerified) {
                LoggerUtil.error(MessageFormat.format("【支付宝】买家：{0} 于 {1} 支付金额 {2} 异步回调验签成功，订单编号：{3} 交易状态：{4}", buyerLogonId, gmtPayment, totalAmount, tradeNo, tradeStatus));
                /*
                 * 异步更新订单状态，需要做幂等
                 */
                //
                //
                //
                //
                //
            } else {
                LoggerUtil.error(MessageFormat.format("【支付宝】买家：{0} 于 {1} 支付金额 {2} 异步回调验签失败，订单编号：{3} 交易状态：{4}", buyerLogonId, gmtPayment, totalAmount, tradeNo, tradeStatus));
            }
        }
    }
}
